package com.jt.utils;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 数据转发
 * <p>太懒了 所以注入bean</p>
 * @author wang xiao
 * date 2023/8/9
 */
@Component
public class ForwardUtil {

    protected static final Logger log = LoggerFactory.getLogger(ForwardUtil.class);


    @Value("${forward.url}")
    private String httpUrl;


    private CloseableHttpClient httpClient;

    private ExecutorService executorService;


    @PostConstruct
    public void initHttpClient(){
        this.httpClient  =  HttpClientBuilder.create().setConnectionTimeToLive(6, TimeUnit.SECONDS)
                .build();
        this.executorService = Executors.newFixedThreadPool(3);
    }

    @PreDestroy
    public void destroyHttpClient() throws IOException {
        this.httpClient.close();
    }


    public void forwardData(ForwardLocationData locationData){
       executorService.execute(()->execForward(locationData));
    }

    private void execForward(ForwardLocationData locationData){
        String msg = JSONObject.toJSONString(locationData);
        log.info("forwarding location data:{}", msg);
        HttpPost httpPost = new HttpPost(buildUri(httpUrl));
        httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpPost.addHeader("accept", "*/*");
        httpPost.addHeader("Connection", "keep-alive");
        BasicResponseHandler handler = new BasicResponseHandler();
        StringEntity entity = new StringEntity(msg, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
          httpClient.execute(httpPost, handler);
        } catch (Exception e) {
            log.error("http send message failed:{}", e.getMessage());
        }
    }

    /**
     * 获取uri
     *
     * @param endpointUrl 用户配置
     * @return URI
     */
    public URI buildUri(String endpointUrl) {
        URI uri = URI.create(endpointUrl);
        if (uri.getScheme() == null || uri.getScheme().isEmpty()) {
            log.error(" Http Transport scheme(protocol) must be provided!");
            throw new IllegalArgumentException("Http Transport scheme(protocol) must be provided!");
        }
        boolean authorityNotValid = uri.getAuthority() == null || uri.getAuthority().isEmpty();
        boolean hostNotValid = uri.getHost() == null || uri.getHost().isEmpty();
        if (authorityNotValid || hostNotValid) {
            log.error("Url string is invalid!");
            throw new IllegalArgumentException("Url string is invalid!\"");
        }
        return uri;
    }

}
